#include "unix_api_adapter.h"

int socket_create() {
	return socket(AF_INET, SOCK_STREAM, 0);
}

int socket_listen(int socket_fd) {
	return listen(socket_fd, 5);
}

int socket_bind(int socketfd, struct socket_address *local_addr) {
	struct sockaddr_in sock_address;
	sock_address.sin_family = AF_INET;
	sock_address.sin_addr.s_addr = inet_addr(local_addr->ip_address);
	sock_address.sin_port = htons(local_addr->port);
	return bind(socketfd, (struct sockaddr*)&sock_address, sizeof(struct sockaddr));
}

int socket_accept(int listen_socket_fd, struct socket_address *peer_address) {
	struct sockaddr_in peer;
	int len = sizeof(peer);
	int ret = accept(listen_socket_fd, (struct sockaddr*)&peer, &len);
	peer_address->port = ntohs(peer.sin_port);
	peer_address->ip_address = inet_ntoa(peer.sin_addr);
	return ret;
}

int socket_connect(int socket_fd, struct socket_address *endpoint_address) {
	struct sockaddr_in sock_address;
	sock_address.sin_family = AF_INET;
	sock_address.sin_addr.s_addr = inet_addr(endpoint_address->ip_address);
	sock_address.sin_port = htons(endpoint_address->port);
	return connect(socket_fd, (struct sockaddr*)&sock_address, sizeof(sock_address));
}

int socket_send(int socket_fd, char *msg, unsigned length) {
	return send(socket_fd, msg, length, NULL);
}

int socket_recv(int socket_fd, char *buf, unsigned length) {
	return recv(socket_fd, buf, length, NULL);
}